package com.esiran.payadmin.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

public class CookieUtil {
    public static void delCookie(HttpServletRequest request,
                                 HttpServletResponse response,
                                 String cookie){
        Cookie targetCookie = getCookie(request,cookie);
        if (targetCookie == null){
            return;
        }
        targetCookie.setMaxAge(0);
        addCookie(response,targetCookie);
    }
    public static Cookie getCookie(HttpServletRequest request, String cookie){
        if (cookie == null){
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null){
            return null;
        }
        return Arrays.stream(cookies).filter(item->item.getName().equals(cookie))
                .findFirst().orElse(null);
    }

    public static String getCookieVal(HttpServletRequest request, String name){
        Cookie cookie = getCookie(request,name);
        if(cookie == null){
            return null;
        }
        return cookie.getValue();
    }
    public static void addCookie(HttpServletResponse response, Cookie cookie){
        if (cookie == null){
            return;
        }
        response.addCookie(cookie);
    }
}
